package com.example.bootdemo5.controller;

import com.example.bootdemo5.common.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Api("上传文件接口")
@RestController
public class UpLoadConroller {



    @Value("${my.uploadFilePath}")
    String  filepath;
    /**
     * key =file
     * @param file
     * @return
     */
    @ApiOperation("上传文件接口")
    @PostMapping("/upload")
    public CommonResult  uploadFile( MultipartFile  file   ){
        if(file!=null){
            try {
                //先判断文件夹是否存在
                File  dir =new File(filepath);
                if(!dir.exists()){
                    dir.mkdir();
                }
                long   l =System.currentTimeMillis(); //无法在高并发的使用
                String filename =l+file.getOriginalFilename();
                File  file1  =new File(filepath+filename);
                file.transferTo(file1);
                return CommonResult.SUCCESS("上传文件成功",filename);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return   CommonResult.FAILURE("上传文件失败");

    }

}
